# -*- coding: utf-8 -*-
from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from service.pagination import PaginationProduct
from service.services import *

def home(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("login/")
    if request.user.is_superuser:
        return HttpResponseRedirect('/admin')
    productsTable, sets, types = getProductTablebyUsername(request.user.username)
    content = {"csv": productsTable, "sets": sets, "types": types, "shopmaker": request.user.username,
               'currency': currency_rate}
    return render_to_response("index.html", content)


def adminhome(request, shopmaker):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("login/")
    if request.user.is_superuser:
        productsTable, sets, types = PaginationProduct(user=shopmaker).getCurrentPageProduct()
        content = {"csv": productsTable, "sets": sets, "types": types, "shopmaker": shopmaker, 'currency': currency_rate
            ,
                   "admin": True}
        return render_to_response("index.html", content)


def test(request):
    return HttpResponse("dfsfsdf")


def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect("/")
    if request.method == "POST":
        user = auth.authenticate(username=request.POST["login[username]"], password=request.POST["login[password]"])
        if user is None:
            valid = validLog(username=request.POST["login[username]"], password=request.POST["login[password]"])
            if valid:
                newuser = User.objects.create_user(username=request.POST["login[username]"], email="support@nadiyno.com"
                    , password=request.POST["login[password]"])
                newuser.is_staff = True
                role, userId = getUsernameRole(request.POST["login[username]"])
                if role == 1 or role == 33:
                    newuser.is_superuser = True
                newuser.save()
                user = auth.authenticate(username=request.POST["login[username]"],
                    password=request.POST["login[password]"])
        if user:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect("/")
            else:
                return render_to_response('login.html', {'error': 'неверный логин или пароль'})
        else:
            return render_to_response('login.html', {'error': 'неверный логин или пароль'})

    return render_to_response('login.html')


def saveTempFile(request, shopmaker):
    """

    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect("login/")
    if request.method == "POST":
        filename = request.POST["filename"]
        content = request.POST["content"]
        contentFile = "\"\",%s\r\n%s" % (getCSVHeader(), content) # contentFile= "%s\r\n%s" % (getCSVHeader(), content)
        if content and filename:
            filename = saveFile(STATICFILES_DIRS[0] + "/xml/" + shopmaker + "/", filename.replace("csv", "xml"),
                csvToXml(contentFile), format="xml")
            return HttpResponse(STATIC_URL + "xml/" + shopmaker + "/" + filename.replace("csv", "xml"))
    return HttpResponse("")


def logout(request):
    if request.user.is_authenticated():
        auth.logout(request)
    return HttpResponseRedirect("/login/")


def admin(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("login/")
    if request.user.is_superuser:
        return render_to_response('views.html', {'shopmakers': getShopmakers(), 'currency': currency_rate})
    return HttpResponseRedirect("/")
